package com.hc.android.research.background;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.net.URI;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import com.hc.android.research.AndroidResearchActivity;
import com.hc.android.research.dom.Item;
import com.hc.android.research.persistence.ResearchDAO;

import android.R;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

public class BackgroundService extends IntentService {

	public BackgroundService() {
		super("Research Android App");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
						
		ResearchDAO researchDAO = new ResearchDAO();
	    List<Item> items = researchDAO.getItems(this);
		
	    int count = 0;
	    if(items != null)
	    {
		    Iterator<Item> itemIter = items.iterator();
		    while(itemIter.hasNext())
		    {
		    	try 
		    	{
			    	Item item = itemIter.next();
			    	URI uri = item.getItemURL();
			    	URL url = new URL(uri.toString());
			    	DataInputStream is = new DataInputStream(new BufferedInputStream(url.openStream()));
			    	
			    	StringBuilder page = new StringBuilder();
			    	String line = null;
			    	while((line = is.readLine()) != null)
			    	{
			    		page.append(line);
			    	}
			    	
			    	int start = page.toString().indexOf("<title>");
			    	int end = page.toString().indexOf("</title>");
			    	String data = page.toString().substring(start, end);
			    	
			    	researchDAO.updateItem(getApplicationContext(), item.getItemID(), item.getItemName(), data, item.getItemURL().toString());
			    	
			    	count++;
		    	}
		    	catch(Exception e)
		    	{
		    		e.printStackTrace();
		    	}		    	
		    }
	    }
	    
	    if(count > 0)
	    {
		    String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager nMan = (NotificationManager)getSystemService(ns);
			int icon = R.id.icon;
			Notification n = new Notification(icon, "Android Research Background Task", System.currentTimeMillis());
			
			Intent intent2 = new Intent(this, AndroidResearchActivity.class);
			PendingIntent pi = PendingIntent.getActivity(this, 0, intent2, 0);
			n.setLatestEventInfo(getApplicationContext(), "Android Research", "You have some new data on " + count + " items", pi);
			nMan.notify(1, n);
	    }
		stopSelf();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		return super.onStartCommand(intent, flags, startId);
	}
}
